using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Betty
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Random rand = new Random();
        int playerScore = 0;
        enum GameStates { TitleScreen, Playing, GameOver };
        GameStates gameState = GameStates.TitleScreen;
        const int pooSize = 40;
        float timeRemaining = 0.0f;
        private const float MAX_TIME_PER_POO = 2.0f;
        float timePerPoo = MAX_TIME_PER_POO;
        Color[] colors = new Color[3] { Color.Red, Color.Green, Color.Blue };
        private Texture2D titleScreen;
        private Texture2D gameOver;
        private Texture2D pooTexture;
        private Texture2D goldenPooTexture;
        private Texture2D dogTexture;
        private Texture2D mouseTexture;
        
        private Rectangle mouseRect;

        List<Poo> pooList;
        List<Dog> dogList;
        private const int MAX_POO = 5;
        private const float MAX_DOG_POO_TIME = 1.5f;
        private const int GOLDEN_RATE = 15;
        

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            this.IsMouseVisible = true;
            graphics.PreferredBackBufferWidth = 800;
            graphics.PreferredBackBufferHeight = 600;
            graphics.ApplyChanges();
            base.Initialize();
            this.IsMouseVisible = false;
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            titleScreen = Content.Load<Texture2D>(@"Textures\TitleScreen");
            gameOver = Content.Load<Texture2D>(@"Textures\GameOver");
            pooTexture = Content.Load<Texture2D>(@"Textures\poo");
            goldenPooTexture = Content.Load<Texture2D>(@"Textures\goldenPoo");
            dogTexture = Content.Load<Texture2D>(@"Textures\dog");
            mouseTexture = Content.Load<Texture2D>(@"Textures\mouse");
            SoundManager.Initialize(Content);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            switch (gameState)
            {
                case GameStates.TitleScreen:
                case GameStates.GameOver:
                    if (Keyboard.GetState().IsKeyDown(Keys.Space))
                    {
                        playerScore = 0;
                        timePerPoo = MAX_TIME_PER_POO;
                        gameState = GameStates.Playing;
                        pooList = new List<Poo>();
                        dogList = new List<Dog>();
                    }
                    break;
                case GameStates.Playing:
                    MouseState mouse = Mouse.GetState();
                    mouseRect = new Rectangle((int)MathHelper.Max(0, mouse.X - mouseTexture.Width/2),
                                            (int)MathHelper.Max(0, mouse.Y - mouseTexture.Height/2),
                                            mouseTexture.Width,
                                            mouseTexture.Height);
                    if(Keyboard.GetState().IsKeyDown(Keys.C))
                        timePerPoo = MAX_TIME_PER_POO;
                    if (timeRemaining <= 0.0f)
                    {
                        int x = rand.Next(0, this.Window.ClientBounds.Width - Dog.dogWidthWithPoo);
                        int y = rand.Next(0, this.Window.ClientBounds.Height - Dog.dogHeight);
                        dogList.Add(new Dog(x + Poo.PooWidth, y, MathHelper.Min(timePerPoo, MAX_DOG_POO_TIME)));
                        timeRemaining = timePerPoo;
                    }
                    Dog[] tempDogList = dogList.ToArray();
                    foreach (Dog curDog in tempDogList)
                    {
                        curDog.timeBeforePoo = MathHelper.Max(0, curDog.timeBeforePoo - (float)gameTime.ElapsedGameTime.TotalSeconds);
                        if (curDog.timeBeforePoo <= 0.3f && !curDog.Pooped)
                        {
                            curDog.Pooped = true;
                            if (pooList.Count() >= MAX_POO)
                            {
                                gameState = GameStates.GameOver;
                                SoundManager.PlayGameOver();
                                break;
                            }
                            bool golden = rand.Next(0, GOLDEN_RATE) == 0;
                            pooList.Add(new Poo(curDog.Rect.X - Poo.PooWidth,
                                                curDog.Rect.Y + Dog.dogHeight - Poo.PooHeight,
                                                golden, timePerPoo));
                        }
                        if (curDog.timeBeforePoo == 0.0f)
                        {
                            dogList.Remove(curDog);
                        }
                    }
                    
                    Poo[] tempPooList = pooList.ToArray();
                    foreach (Poo curPoo in tempPooList)
                    {
                        if ((mouse.LeftButton == ButtonState.Pressed) && curPoo.Contains(mouse.X, mouse.Y))
                        {
                            playerScore++;
                            timeRemaining = 0.0f;
                            timePerPoo = MathHelper.Max(timePerPoo - (0.05f * (1+playerScore/20)), MathHelper.Max(0.4f, 1 - ((float)playerScore) / 100));
                            if (curPoo.isGolden)
                            {
                                timePerPoo = MAX_TIME_PER_POO;
                                SoundManager.PlayExplosion();
                            }
                            else
                            {
                                SoundManager.PlayShot();
                            }
                            pooList.Remove(curPoo);
                            break;
                        }
                        else if (curPoo.isGolden)
                        {
                            curPoo.timeout = MathHelper.Max(0, curPoo.timeout - (float)gameTime.ElapsedGameTime.TotalSeconds);
                            if (curPoo.timeout == 0.0f)
                            {
                                pooList.Remove(curPoo);
                            }
                        }
                    }
                    timeRemaining = MathHelper.Max(0, timeRemaining - (float)gameTime.ElapsedGameTime.TotalSeconds);
                    this.Window.Title = "Score : " + playerScore.ToString() + "     Timeout: " + timePerPoo.ToString();
                    break;
            }
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            if (gameState == GameStates.TitleScreen)
            {
                spriteBatch.Begin();
                spriteBatch.Draw(titleScreen,
                    new Rectangle(0, 0,
                        this.Window.ClientBounds.Width,
                        this.Window.ClientBounds.Height),
                    Color.White);
                spriteBatch.End();
            }

            else if (gameState == GameStates.Playing)
            {
                spriteBatch.Begin();
                foreach (Poo curPoo in pooList)
                {
                    if(curPoo.isGolden)
                        spriteBatch.Draw(goldenPooTexture, curPoo.Rect, Color.White);
                    else
                        spriteBatch.Draw(pooTexture, curPoo.Rect, Color.White);
                }
                foreach (Dog curDog in dogList)
                {
                    spriteBatch.Draw(dogTexture, curDog.Rect, Color.White);
                }
                // draw mouse pointer
                spriteBatch.Draw(mouseTexture, mouseRect, Color.White);

                spriteBatch.End();
            }
            else if (gameState == GameStates.GameOver)
            {
                spriteBatch.Begin();
                spriteBatch.Draw(gameOver,
                    new Rectangle(0, 0,
                        this.Window.ClientBounds.Width,
                        this.Window.ClientBounds.Height),
                    Color.White);
                spriteBatch.End();
            }
            base.Draw(gameTime);
        }
    }
}

